#include "EventWrapper.h"
#include "SoundWrapper.h"
#include "GameEngine.h"
#include "Window.h"
#include "MainMenuState.h"

#include <ctime>
#include <cstdlib>

GameEngine::GameEngine()
        : window(new Window(800, 600)), programRunning(true), currentGameState(NULL)
{
}

void GameEngine::start()
{
    init();
    while (programRunning)
    {
        handleEvents();
        unsigned long tick = clock.getMSeconds();
        setGameState(currentGameState->update(tick));
        window->update(tick);
        window->render();
    }
    clean();
}

void GameEngine::setGameState(GameState* state)
{
    if (state != NULL && state != currentGameState)
    {
        window->eraseChildren();
        delete currentGameState;
        currentGameState = state;
        currentGameState->init();
        window->addChild(currentGameState->createGraphics());
    }
}

void GameEngine::init()
{
    GraphicsWrapper::init();
    SoundWrapper::init();
    window->open();
    setGameState(new MainMenuState());
    srand(time(NULL));
}

void GameEngine::clean()
{
    delete window;
    GraphicsWrapper::quit();
    SoundWrapper::quit();
}

void GameEngine::handleEvents()
{
    Events events = EventWrapper::getEvents();
    for (Events::iterator it = events.begin(); it != events.end(); ++it)
    {
        handleEvent(**it);
        delete(*it);
    }
}

void GameEngine::quit()
{
    programRunning = false;
}

void GameEngine::handleEvent(const Event& event)
{
    event.visitGameEngine(this);
    window->traverse(event);
    setGameState(currentGameState->handleEvent(event));
}

GameEngine::~GameEngine()
{
}
